package com.baomidou.springwind.controller;

import com.baomidou.framework.controller.SuperController;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.kisso.common.encrypt.SaltEncoder;
import com.baomidou.kisso.web.waf.request.WafRequestWrapper;
import com.baomidou.springwind.common.MyCaptcha;
import com.baomidou.springwind.common.enums.UserType;
import com.baomidou.springwind.entity.User;
import com.baomidou.springwind.entity.UserRole;
import com.baomidou.springwind.msg.MailSender;
import com.baomidou.springwind.service.IUserRoleService;
import com.baomidou.springwind.service.IUserService;
import com.baomidou.springwind.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * <p>
 * 账户相关操作
 * </p>
 *
 * @author luoxin
 * @Date 2016-04-13
 */
@Controller
@RequestMapping("/account")
public class AccountController extends SuperController {

    //锁定用户标记
    private static final String LOCKSCREEN_USER_FLAG = "LockscreenUserFlag";

    @Autowired
    protected IUserService userService;

    @Autowired
    protected IUserRoleService userRoleService;

    @Autowired
    private MailSender mailSender;

    @Value("${mail.recipient}")
    private String recipient;

    /**
     * 登录
     */
    @ResponseBody
    @Login(action = Action.Skip)
    @Permission(action = Action.Skip)
    @RequestMapping("/doLogin")
    public String doLogin(Model model, User user1) throws IOException {
        /**
         * 过滤 XSS SQL 注入
         */
        WafRequestWrapper wr = new WafRequestWrapper(request);
        String ctoken = wr.getParameter("ctoken");
        String captcha = wr.getParameter("captcha");
        if (StringUtils.isNotBlank(ctoken)
                && StringUtils.isNotBlank(captcha)
                && MyCaptcha.getInstance().verification(wr, ctoken, captcha)) {
            return callbackFail("验证码错误");
        } else {
            String loginName = wr.getParameter("loginName");
            loginName = new String(loginName.getBytes("iso-8859-1"), "utf-8");
            String password = wr.getParameter("password");
            User user = userService.selectByLoginName(loginName);
//            System.out.println("---------------" + SaltEncoder.md5SaltValid(loginName, user.getPassword(), password));
            if(user==null){
                return callbackFail("没有该用户，请注册");
            }
            if(SaltEncoder.md5SaltValid(loginName, user.getPassword(), password)==false){
                return callbackFail("用户密码错误，请重新输入密码");
            }
            if(user.getStatus() != 1){
                return callbackFail("正在审核，请等待");
            }
            SSOToken st = new SSOToken(request);
            st.setId(user.getId());
            st.setData(loginName);
            // 记住密码，设置 cookie 时长 1 周 = 604800 秒
            String rememberMe = wr.getParameter("rememberMe");
//          if ("on".equals(rememberMe)) {
//          request.setAttribute(SSOConfig.SSO_COOKIE_MAXAGE, 604800);
//          }
            SSOHelper.setSSOCookie(request, response, st, true);
        }
        return callbackSuccess("成功");
    }

    /**
     * 注册
     */
    @ResponseBody
    @Login(action = Action.Skip)
    @Permission(action = Action.Skip)
    @RequestMapping("/register")
    public String register(Model model, User user) {
        if (isPost()) {
            User existUser = userService.selectByLoginName(user.getEmail().toString());
            if (existUser == null) {
                user.setPassword(SaltEncoder.md5SaltEncode(user.getEmail(), user.getPassword()));
                user.setType(UserType.MEMBER1.key());
                user.setCrTime(new Date());
                user.setLastTime(user.getCrTime());
                user.setStatus(2);
                boolean success = userService.insert(user);
                sendMsg(user);
                //todo 写入权限，设置日期
                if (success) {
                    UserRole userRole = new UserRole();
                    userRole.setUid(user.getId());
                    userRole.setRid(3L);
                    userRoleService.insert(userRole);
                }
            } else {
                return callbackFail("注册邮箱号【" + user.getEmail() + "】已存在！");
            }
        }
        return callbackSuccess("成功");
    }

    private void sendMsg(User user) {
        if (StringUtils.isEmpty(recipient)) {
            return;
        }
        try {
            //todo具体内容可以添加
            String content = String.format("%s 的 %s 于 %s 申请试用，请及时审批",user.getCompany(),user.getName(), DateUtils.formatCHS(DateUtils.getNow()));
            mailSender.sendMail("试用申请！！", content, recipient.split("\\s+"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 退出
     */
    @Login(action = Action.Skip)
    @Permission(action = Action.Skip)
    @RequestMapping("/logout")
    public String logout(Model model) {
        SSOHelper.clearLogin(request, response);
        return redirectTo("/account/login1.html");
    }

    /**
     * 锁定
     */
    @Login(action = Action.Skip)
    @Permission(action = Action.Skip)
    @RequestMapping("/lockscreen")
    public String lockscreen(Model model, String password) {
        HttpSession session = request.getSession();
        String loginName = (String) session.getAttribute(LOCKSCREEN_USER_FLAG);
        if (StringUtils.isBlank(loginName)) {
            SSOToken st = SSOHelper.getToken(request);
            if (st == null) {
                /* 未登录 */
                return redirectTo("/account/login.html");
            }
            loginName = st.getData();
            session.setAttribute(LOCKSCREEN_USER_FLAG, loginName);
            ;
            SSOHelper.clearLogin(request, response);
        } else if (StringUtils.isNotBlank(password) && isPost()) {
            /*
             * 锁定页面登录
             */
            User user = userService.selectByLoginName(loginName);
            if (user != null && SaltEncoder.md5SaltValid(loginName, user.getPassword(), password)) {
                /*
                 * 登录成功，进入后台
                 */
                SSOToken st = new SSOToken(request);
                st.setId(user.getId());
                st.setData(loginName);
                SSOHelper.setSSOCookie(request, response, st, true);
                return redirectTo("/index.html");
            }
        }

        model.addAttribute("loginName", loginName);
        return "/lockscreen";
    }

}
